import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ConfirmDialogService } from './confirm-dialog/confirm-dialog.service';

@Injectable({
  providedIn: 'root'
})
/**
 * 描述：公共服务http请求配置
 * 公司：xxx有限公司
 * 版权：xxx2020
 * 作者：oyjl
 * 时间：2020-04-26 16:25:22
 */
export class CommonService {

  public cacheData: any; // 缓存数据
  constructor(
    private http: HttpClient,
    public confirmDialogService: ConfirmDialogService,
    public router: Router) { }

  /**
   * 描述：获取列表数据
   * 作者：oyjl
   * 时间：2020-04-26 16:25:57
   */
  // TODO：统一的分页参数查询未处理
  public getData(url, req, key?: string) {
    req.accountId = sessionStorage.getItem('accountId');
    return this.http.post(url, req).pipe(
      map((res: any) => {
        // 校验accountId是否存在，如果不存在则返回登录首页重新登录
        if (!req.accountId) {
          this.router.navigateByUrl('/mobile/login');
        }
        let data = res;
        if (res.operateSuccess) {
          if (!key) {
            key = 'pageModel.rows';
          }
          if (key) {
            const arr = key.split('.');
            for (const i of arr) {
              data = data[i];
            }
          }
        } else {
          this.confirmDialogService.confirm({
            type: 'error',
            headText: '错误',
            contentText: res.opMsg || res.msg
          });
        }
        return data;
      }),
      catchError((res: HttpResponse<any>) => {
        const errMsg = res ? `${res.status} - ${res.statusText}` : '服务器错误!';
        this.confirmDialogService.confirm({
          type: 'error',
          headText: '错误',
          contentText: errMsg
        });
        return of(res);
      })
    );
  }

  /**
   * 描述：发送post请求
   * 作者：oyjl
   * 时间：2020-04-28 14:43:10
   */
  public sendPost(url, req) {
    req.accountId = sessionStorage.getItem('accountId');
    return this.http.post(url, req).pipe(map((res: any) => {
      // 校验accountId是否存在，如果不存在则返回登录首页重新登录
      if (!req.accountId) {
        this.router.navigateByUrl('/mobile/login');
      }
      if (!res.operateSuccess) {
        this.confirmDialogService.confirm({
          type: 'error',
          headText: '错误',
          contentText: res.opMsg || res.msg
        });
      }
      return res;
    }),
      catchError((res: HttpResponse<any>) => {
        const errMsg = res ? `${res.status} - ${res.statusText}` : '服务器错误!';
        this.confirmDialogService.confirm({
          type: 'error',
          headText: '错误',
          contentText: errMsg
        });
        return of(res);
      })
    );
  }
}
